package com.umeox.watch.moto.launcher.ui;


import static com.umeox.watch.moto.launcher.constant.Constant.TAG_LAUNCHER;
import static com.umeox.watch.moto.pedometer.util.ICache.KEY_DEVICE_DATA;

import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.WindowManager;

import com.umeox.moto.common.log.Logger;
import com.umeox.moto.common.utils.AndroidUtils;
import com.umeox.moto.common.utils.NetworkUtil;
import com.umeox.moto.common.utils.SystemUtils;
import com.umeox.moto.watch.themes.app.ThemeAppCompatActivity;
import com.umeox.watch.moto.dataservice.DataProvider;
import com.umeox.watch.moto.dataservice.constants.Constants;
import com.umeox.watch.moto.launcher.R;
import com.umeox.watch.moto.launcher.constant.Constant;
import com.umeox.watch.moto.pedometer.util.CacheImpl;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class DetectSignalActivity extends ThemeAppCompatActivity {

    protected static final String TAG = "DetectSignalActivity";
    private int recLen = 0;
    private ScheduledExecutorService executor;
    private DeviceInitReceiver mDeviceInitReceiver = new DeviceInitReceiver();

    private void startNetActivity() {
        startActivity(new Intent(DetectSignalActivity.this, NetworkNormalActivity.class));
        DetectSignalActivity.this.finish();
    }

    public static void start(Context context) {
        context.startActivity(new Intent(context, DetectSignalActivity.class));
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.detect_signal_activity);
        ContentValues contentValues = DataProvider.getDeviceCode(AndroidUtils.getDeviceId());

        if (contentValues != null && NetworkUtil.isAvailable(this)) {
            String bindCode = contentValues.getAsString(DataProvider.DeviceCodeProvider.BIND_CODE);
            Long expiredTime = contentValues.getAsLong(DataProvider.DeviceCodeProvider.EXPIRED_TIME);
            long currentTime = System.currentTimeMillis();
            if (bindCode != null && expiredTime >= currentTime) {
                CacheImpl.getInstance().put(KEY_DEVICE_DATA, true);
            }
        }
        executor = Executors.newScheduledThreadPool(1);
        executor.scheduleAtFixedRate(
                () -> {
                    recLen++;
                    boolean syncedData = CacheImpl.getInstance().get(KEY_DEVICE_DATA, false);
                    Logger.e(TAG_LAUNCHER, "DetectSignal : " + recLen + " " + syncedData);
                    if (syncedData) {
                        executor.shutdown();
                        startNetActivity();
                        return;
                    }

                    if (recLen % 2 == 0) {
                        final boolean connectInternet = SystemUtils.isConnectInternet(getApplicationContext());
                        if (connectInternet) {
                            Intent launchIntent = new Intent();
                            launchIntent.setAction(Constant.IntentConstant.INTENT_LAUNCHER_LAUNCHED);
                            sendBroadcast(launchIntent);
                        }
                    }
                    if (recLen > 40) {
                        executor.shutdown();
                        startActivity(new Intent(DetectSignalActivity.this, NoNetworkActivity.class));
                        DetectSignalActivity.this.finish();
                    }
                },
                0,
                1000,
                TimeUnit.MILLISECONDS);

        registerDeviceInitReceiver();
    }


    private void registerDeviceInitReceiver() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constants.ACTION_DEVICE_NOT_INIT);
        registerReceiver(mDeviceInitReceiver, intentFilter);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (executor != null) {
            executor.shutdownNow();
        }
        if (mDeviceInitReceiver != null) {
            unregisterReceiver(mDeviceInitReceiver);
        }
    }

    private class DeviceInitReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (executor != null) {
                executor.shutdownNow();
            }
            QrActivity.launch(DetectSignalActivity.this);
            finish();
        }
    }


    @Override
    protected void registerUnbindAndDisableReceiver(boolean register) {
    }

    @Override
    public void onBackPressed() {

    }
}
